<?php

namespace app\admin\controller;

use app\models\Admin;
use app\models\{
    User as Users,
    Moneylog,
    Shopinfo,
    Project,
    MerchantItem,
    Config
};
use app\facade\Redis;
use think\Db;

class User extends Base
{


    public function index()
    {
        $data = input('param.');
        $model = new Users();
        $list = $model->order('id desc');
        if (isset($data['title'])) {
            $list = $list->where('mobile|nickname', 'like', '%' . $data['title'] . '%');
        }
        $list = $list->paginate(20, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    //添加修改
    public function user_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = input('post.');
            //判断手机号码是否存在
            $user = (new Users())->where('mobile', $data['mobile'])->find();
            if (empty($data['id'])) {
                if (empty($data['password'])) {
                    return json(['status' => 1, 'msg' => '新用户密码不能为空']);
                }
                if (!empty($user)) {
                    return json(['status' => 1, 'msg' => '账号已存在']);
                }
                $data['code'] = recode(new Users());
                $data['password'] = md5(md5($data['password']));
                $result = (new Users())->allowField(true)->save($data);
            } else {
                if (!empty($user) && $user['id'] != $data['id']) {
                    return json(['status' => 1, 'msg' => '修改手机账号已存在']);
                }
                if (!empty($data['password'])) {
                    $data['password'] = md5(md5($data['password']));
                }
                $result = (new Users())->allowField(true)->save($data, ['id' => $data['id']]);
            }
            if ($result) {
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $row = (new Users())->where('id', $id)->find();
            return view('', ['row' => $row]);
        }
    }
}
